import json
from django.http import JsonResponse, HttpResponse
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from course.models import *
import os
from datetime import datetime
import glob
from course.modelmanager import ModelManager

# Create your views here.
static_file_path = 'static/files/'


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def add_chapter(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    name = json_dict.get('name', None)
    if name:
        p = Chapter.objects.create(name=name)
        p.save()
        return JsonResponse(
            {
                'code': 200,
                'message': '请求成功',
            }
        )
    else:
        return JsonResponse(
            {
                'code': 500,
                'message': '请求参数错误'
            }
        )


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_chapter(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    if key:
        try:
            Chapter.objects.filter(id=key).delete()
            return JsonResponse(
                {
                    'code': 200,
                    'message': '删除成功'
                }
            )
        except:
            return JsonResponse(
                {
                    'code': 500,
                    'message': '没有此章节'
                }
            )
    else:
        return JsonResponse(
            {
                'code': 500,
                'message': '请求参数错误'
            }
        )


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def modify_chapter(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    name = json_dict.get('name', None)
    if key and name:
        try:
            print(key, name)
            chapter = Chapter.objects.get(id=key)
            chapter.name = name
            chapter.save()
            return JsonResponse(
                {
                    'code': 200,
                    'message': '修改成功'
                }
            )
        except:
            return JsonResponse(
                {
                    'code': 500,
                    'message': '没有此章节'
                }
            )
    else:
        return JsonResponse(
            {
                'code': 500,
                'message': '请求参数错误'
            }
        )


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@authentication_classes((JSONWebTokenAuthentication,))
def query_chapter(request):
    chapters = Chapter.objects.filter()
    data = list()
    for chapter in chapters:
        p = dict()
        p['name'] = chapter.name
        p['key'] = chapter.id
        p['modify_time'] = chapter.UpdatedAt
        data.append(p)
    return JsonResponse(
        {
            'code': 200,
            'message': '请求成功',
            'data': data
        }
    )


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@authentication_classes((JSONWebTokenAuthentication,))
def query_section(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    chapter_key = json_dict.get('chapter_key', None)
    sections = Section.objects.filter(chapter__id=chapter_key)
    data = list()
    for section in sections:
        p = dict()
        p['chapter_key'] = chapter_key
        p['key'] = section.id
        p['name'] = section.name
        p['modify_time'] = section.UpdatedAt
        p['file_name'] = section.file_name
        url = static_file_path + 'courseware/' + str(section.id)
        if os.path.exists(url):
            p['page_numbers'] = len(glob.glob(pathname=url + '/*.*'))
        else:
            p['page_numbers'] = 0
        data.append(p)
    return JsonResponse(
        {
            'code': 200,
            'message': '请求成功',
            'data': data
        }
    )


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def add_section(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    chapter_key = json_dict.get('chapter_key', None)
    name = json_dict.get('name', None)
    if chapter_key and name:
        try:
            chapter = Chapter.objects.get(id=chapter_key)
            section = Section.objects.create(chapter=chapter, name=name)
            section.save()
            return JsonResponse({'code': 200, 'message': '请求成功'})
        except Exception:
            return JsonResponse({'code': 500, 'message': 'chapter key错误'})
    else:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_section(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    if key:
        try:
            Section.objects.get(id=key).delete()
            return JsonResponse({'code': 200, 'message': '请求成功'})
        except Exception:
            return JsonResponse({'code': 500, 'message': 'key错误'})
    else:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def modify_section(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    name = json_dict.get('name', None)
    if key and name:
        try:
            section = Section.objects.get(id=key)
            section.name = name
            section.save()
            return JsonResponse({'code': 200, 'message': '请求成功'})
        except Exception:
            return JsonResponse({'code': 500, 'message': 'key错误'})
    else:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@authentication_classes((JSONWebTokenAuthentication,))
def query_all(request):
    chapters = Chapter.objects.filter()
    data = list()
    cnt = 0
    prosort = 0
    for chapter in chapters:
        p = dict()
        p['key'] = chapter.id
        p['name'] = chapter.name
        p['modify_time'] = chapter.UpdatedAt
        p['isEdit'] = False
        cnt += 1
        p['id'] = cnt
        prosort += 1
        p['ProSort'] = prosort
        q = list()
        sections = Section.objects.filter(chapter__id=chapter.id)
        for section in sections:
            o = dict()
            o['chapter_key'] = chapter.id
            o['key'] = section.id
            o['name'] = section.name
            o['modify_time'] = section.UpdatedAt
            o['isEdit'] = False
            o['file_name'] = section.file_name
            url = static_file_path + 'courseware/' + str(section.id)
            if os.path.exists(url):
                o['page_numbers'] = len(glob.glob(pathname=url + '/*.*'))
            else:
                o['page_numbers'] = 0
            cnt += 1
            o['id'] = cnt
            q.append(o)
        p['children'] = q
        data.append(p)
    return JsonResponse(
        {
            'code': 200,
            'message': '请求成功',
            'data': data
        }
    )


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def add_sectionfile(request):
    key = request.POST.get("key")
    try:
        key = int(key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    sections = Section.objects.filter(id=key)
    if len(sections) == 0:
        return JsonResponse({'code': 500, 'message': '该小节未找到'})
    files = request.FILES.getlist("file")
    if len(files) == 0:
        return JsonResponse({'code': 500, 'message': '文件缺失'})
    f = files[0]
    section = sections[0]
    url = static_file_path + 'courseware/' + str(key)
    try:
        os.remove(section.url)
        os.remove(static_file_path + 'courseware/' + str(key))
    except Exception:
        pass
    section.url = url + "_" + f.name
    section.file_name = f.name
    section.save()
    d = open(section.url, 'wb+')
    for chunk in f.chunks():
        d.write(chunk)
    d.close()
    url = static_file_path + "backup/" + str(key) + "_" + str(datetime.now()).replace(":", '-').\
        replace(' ', '-').replace('.', '-') + '_' + f.name
    filebackup = FileBackUp.objects.create(mytype=3, name=str(key) + "_" + str(datetime.now()).replace(":", '-').\
                                           replace(' ', '-').replace('.', '-') + '_' + f.name, url=url)
    filebackup.save()
    d = open(url, 'wb+')
    for chunk in f.chunks():
        d.write(chunk)
    d.close()
    if f.name.endswith('.ppt') or f.name.endswith('.pptx'):
        import pythoncom
        pythoncom.CoInitialize()
        url = os.path.join(os.getcwd(), section.url)
        import win32com.client
        ppt_app = win32com.client.Dispatch('PowerPoint.Application')
        ppt = ppt_app.Presentations.Open(url)
        ppt.SaveAs(os.path.join(os.getcwd(), static_file_path + 'courseware/' + str(key) + '.jpg'), 17)
        ppt_app.Quit()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@authentication_classes((JSONWebTokenAuthentication,))
def get_sectionfile_page(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    page_number = json_dict.get('page_number', None)
    if not key or not page_number:
        return JsonResponse({'code': 500, 'message': '请求参数缺失'})
    sections = Section.objects.filter(id=key)
    if len(sections) == 0:
        return JsonResponse({'code': 500, 'message': '小节key错误'})
    try:
        url = static_file_path + 'courseware/' + str(key) + '/幻灯片' + str(page_number) + '.JPG'
        actions = SectionAction.objects.filter(section=sections[0], page=page_number)
        if len(actions) == 0:
            data = dict()
            data['url'] = url
            data['attachment_type'] = 0
            return JsonResponse(
                {
                    'code': 200,
                    'message': '请求成功',
                    'data': data,
                }
            )
        else:
            action = actions[0]
            if action.mytype == 3:
                data = dict()
                data['url'] = url
                data['attachment_type'] = action.mytype
                data['model_key'] = action.model.id
                data['attachment_key'] = action.id
                return JsonResponse(
                    {
                        'code': 200,
                        'message': '请求成功',
                        'data': data,
                    }
                )
            else:
                data = dict()
                data['url'] = url
                data['attachment_type'] = action.mytype
                data['attachment_url'] = action.url
                data['attachment_key'] = action.id
                return JsonResponse(
                    {
                        'code': 200,
                        'message': '请求成功',
                        'data': data,
                    }
                )
    except Exception:
        return JsonResponse({'code': 500, 'message': '文件不存在'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def add_model(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    name = json_dict.get('name', None)
    classname = json_dict.get('classname', None)
    if not name or not classname:
        return JsonResponse({'code': 500, 'message': '请求参数缺失'})
    model = MyModel.objects.create(name=name, classname=classname)
    model.save()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def modify_model(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    name = json_dict.get('name', None)
    classname = json_dict.get('classname', None)
    models = MyModel.objects.filter(id=key)
    if len(models) == 0:
        return JsonResponse({'code': 500, 'message': '请求参数key未找到'})
    model = models[0]
    if name:
        model.name = name
    if classname:
        model.classname = classname
    model.save()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_model(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    MyModel.objects.filter(id=key).delete()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@authentication_classes((JSONWebTokenAuthentication,))
def query_model(request):
    models = MyModel.objects.filter()
    data = list()
    for model in models:
        p = dict()
        p['name'] = model.name
        p['key'] = model.id
        p['classname'] = model.classname
        p['UpdateTime'] = model.UpdatedAt
        data.append(p)
    return JsonResponse({'code': 200, 'message': '请求成功', 'data': data})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@authentication_classes((JSONWebTokenAuthentication,))
def download_file(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    if not key:
        return JsonResponse({'code': 500, 'message': '请求参数缺失'})
    sections = Section.objects.filter(id=key)
    if len(sections) == 0:
        return JsonResponse({'code': 500, 'message': 'key不存在'})
    section = sections[0]
    url = section.url
    return JsonResponse({'code': 200, 'message': '请求成功', 'data': url})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def upload_attachment(request):
    key = request.POST.get("key")
    page_number = request.POST.get("page_number")
    mytype = request.POST.get("mytype")
    if not key or not page_number or not mytype:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    try:
        key = int(key)
        page_number = int(page_number)
        mytype = int(mytype)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数类型错误'})
    sections = Section.objects.filter(id=key)
    if len(sections) == 0:
        return JsonResponse({'code': 500, 'message': '该小节未找到'})
    models = MyModel.objects.filter()
    actions = SectionAction.objects.filter(page=page_number, section=sections[0])
    if len(actions) == 0:
        action = SectionAction.objects.create(mytype=mytype, page=page_number,
                                              section=sections[0], model=models[0])
    else:
        action = actions[0]
        if action.mytype == 1 or action.mytype == 2:
            try:
                os.remove(action.url)
            except Exception:
                pass
        action.mytype = mytype
    if mytype == 1 or mytype == 2:
        files = request.FILES.getlist("file")
        if len(files) == 0:
            return JsonResponse({'code': 500, 'message': '文件缺失'})
        f = files[0]
        action.url = static_file_path + 'action/' + str(key) + "_" + f.name
        action.name = f.name
        action.save()
        d = open(action.url, 'wb+')
        for chunk in f.chunks():
            d.write(chunk)
        d.close()
        url = static_file_path + "backup/" + str(key) + "_" + str(datetime.now()).replace(":", '-'). \
            replace(' ', '-').replace('.', '-') + '_' + f.name
        filebackup = FileBackUp.objects.create(mytype=mytype, name=str(key) + "_" + str(datetime.now()).replace(":", '-'). \
                                               replace(' ', '-').replace('.', '-') + '_' + f.name, url=url)
        filebackup.save()
        d = open(url, 'wb+')
        for chunk in f.chunks():
            d.write(chunk)
        d.close()
        return JsonResponse({'code': 200, 'message': '请求成功'})
    elif mytype == 3:
        model_key = request.POST.get("model_key")
        if not model_key:
            return JsonResponse({'code': 500, 'message': '请求参数错误'})
        models = MyModel.objects.filter(id=model_key)
        if len(models) == 0:
            return JsonResponse({'code': 500, 'message': '此model不存在'})
        model = models[0]
        action.name = model.name
        action.model = model
        action.save()
        return JsonResponse({'code': 200, 'message': '请求成功'})
    else:
        return JsonResponse({'code': 500, 'message': '请求type错误'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_attachment(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    if not key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    SectionAction.objects.filter(id=key).delete()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, ))
@authentication_classes((JSONWebTokenAuthentication,))
def query_example(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    section_key = json_dict.get('section_key', None)
    if not section_key:
        return JsonResponse({'code': 500, 'message': '请求参数缺失'})
    examples = Example.objects.filter(section__id=section_key)
    data = list()
    for example in examples:
        p = dict()
        p['key'] = example.id
        p['section_key'] = example.section.id
        p['model_key'] = example.mymodel.id
        p['name'] = example.name
        p['description'] = example.description
        p['UpdateTime'] = example.UpdatedAt
        q = list()
        for epp in example.param_pictures.all():
            tmp_dict = dict()
            tmp_dict['url'] = epp.url
            tmp_dict['key'] = epp.id
            tmp_dict['file_name'] = epp.file_name
            tmp_dict['UpdateTime'] = epp.UpdatedAt
            q.append(tmp_dict)
        p['param_pictures'] = q
        q = list()
        for epp in example.func_pictures.all():
            tmp_dict = dict()
            tmp_dict['url'] = epp.url
            tmp_dict['key'] = epp.id
            tmp_dict['file_name'] = epp.file_name
            tmp_dict['UpdateTime'] = epp.UpdatedAt
            q.append(tmp_dict)
        p['func_pictures'] = q
        q = list()
        for epp in example.params.all():
            tmp_dict = dict()
            tmp_dict['name'] = epp.name
            tmp_dict['pagename'] = epp.pagename
            tmp_dict['default_value'] = epp.default_value
            tmp_dict['key'] = epp.id
            tmp_dict['UpdateTime'] = epp.UpdatedAt
            q.append(tmp_dict)
        p['params'] = q
        data.append(p)
    return JsonResponse({'code': 200, 'message': '请求成功', 'data': data})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def add_example(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    section_key = json_dict.get('section_key', None)
    model_key = json_dict.get('model_key', None)
    name = json_dict.get('name', None)
    description = json_dict.get('description', None)
    if not section_key or not model_key or not name or not description:
        return JsonResponse({'code': 500, 'message': '请求参数缺失'})
    try:
        section = Section.objects.get(id=section_key)
        model = MyModel.objects.get(id=model_key)
        example = Example.objects.create(name=name, description=description,
                                         section=section, mymodel=model)
        example.save()
    except Exception:
        return JsonResponse({'code': 500, 'message': 'key参数错误'})
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_example(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    if not key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    Example.objects.filter(id=key).delete()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def modify_example(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    name = json_dict.get('name', None)
    description = json_dict.get('description', None)
    section_key = json_dict.get('section_key', None)
    try:
        example = Example.objects.get(id=key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    if name:
        example.name = name
    if description:
        example.description = description
    if section_key:
        sections = Section.objects.filter(id=section_key)
        if len(sections) == 0:
            return JsonResponse({'code': 500, 'message': '未找到对应小节'})
        example.section = sections[0]
    example.save()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def add_param_picture(request):
    example_key = request.POST.get("example_key")
    try:
        example_key = int(example_key)
        example = Example.objects.get(id=example_key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    files = request.FILES.getlist("file")
    if len(files) == 0:
        return JsonResponse({'code': 500, 'message': '文件缺失'})
    f = files[0]
    epp = ExampleParamPicture.objects.create(example=example, file_name=f.name)
    epp.save()
    url = static_file_path + 'example_param/' + str(epp.id) + '_' + f.name
    epp.url = url
    epp.save()
    d = open(url, 'wb+')
    for chunk in f.chunks():
        d.write(chunk)
    d.close()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def modify_param_picture(request):
    key = request.POST.get("key")
    try:
        key = int(key)
        epp = ExampleParamPicture.objects.get(id=key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    files = request.FILES.getlist("file")
    if len(files) == 0:
        return JsonResponse({'code': 500, 'message': '文件缺失'})
    f = files[0]
    try:
        os.remove(epp.url)
    except Exception:
        pass
    url = static_file_path + 'example_param/' + str(epp.id) + '_' + f.name
    epp.url = url
    epp.file_name = f.name
    epp.save()
    d = open(url, 'wb+')
    for chunk in f.chunks():
        d.write(chunk)
    d.close()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_param_picture(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    if not key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    ExampleParamPicture.objects.filter(id=key).delete()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def add_func_picture(request):
    example_key = request.POST.get("example_key")
    try:
        example_key = int(example_key)
        example = Example.objects.get(id=example_key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    files = request.FILES.getlist("file")
    if len(files) == 0:
        return JsonResponse({'code': 500, 'message': '文件缺失'})
    f = files[0]
    epp = ExampleFuncPicture.objects.create(example=example, file_name=f.name)
    epp.save()
    url = static_file_path + 'example_func/' + str(epp.id) + '_' + f.name
    epp.url = url
    epp.save()
    d = open(url, 'wb+')
    for chunk in f.chunks():
        d.write(chunk)
    d.close()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def modify_func_picture(request):
    key = request.POST.get("key")
    try:
        key = int(key)
        epp = ExampleFuncPicture.objects.get(id=key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    files = request.FILES.getlist("file")
    if len(files) == 0:
        return JsonResponse({'code': 500, 'message': '文件缺失'})
    f = files[0]
    try:
        os.remove(epp.url)
    except Exception:
        pass
    url = static_file_path + 'example_func/' + str(epp.id) + '_' + f.name
    epp.url = url
    epp.file_name = f.name
    epp.save()
    d = open(url, 'wb+')
    for chunk in f.chunks():
        d.write(chunk)
    d.close()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_func_picture(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    if not key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    ExampleFuncPicture.objects.filter(id=key).delete()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def add_param(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    example_key = json_dict.get('example_key', None)
    name = json_dict.get('name', None)
    default_value = json_dict.get('default_value', None)
    pagename = json_dict.get('pagename', None)
    if not example_key or not name or default_value is None or pagename is None:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    try:
        example = Example.objects.get(id=example_key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    param = ExampleParam.objects.create(example=example, name=name,
                                        default_value=default_value, pagename=pagename)
    param.save()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def modify_param(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    name = json_dict.get('name', None)
    default_value = json_dict.get('default_value', None)
    if not key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    try:
        param = ExampleParam.objects.get(id=key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    if name:
        param.name = name
    if default_value is not None:
        param.default_value = default_value
    param.save()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated, IsAdminUser))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_param(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    key = json_dict.get('key', None)
    if not key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    ExampleParam.objects.filter(id=key).delete()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def add_note(request):
    user_key = request.POST.get("user_key")
    content = request.POST.get("content")
    section_key = request.POST.get("section_key")
    files = request.FILES.getlist("file")
    if user_key is None or content is None or section_key is None or files is None:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    try:
        user_key = int(user_key)
        section_key = int(section_key)
        myuser = MyUser.objects.get(id=user_key)
        section = Section.objects.get(id=section_key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    note = Note.objects.create(content=content, user=myuser, section=section)
    note.save()
    for i in range(len(files)):
        f = files[i]
        url = static_file_path + 'note_picture/' + str(note.id) + '_' + str(i) + '_' + f.name
        if not (f.name.endswith('.jpg') or f.name.endswith('.jpeg') or f.name.endswith('.png')):
            continue
        np = NotePicture.objects.create(url=url, file_name=f.name, note=note)
        np.save()
        d = open(url, 'wb+')
        for chunk in f.chunks():
            d.write(chunk)
        d.close()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def change_note_status(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    note_key = json_dict.get('note_key', None)
    is_public = json_dict.get('is_public', None)
    if not note_key or is_public is None:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    try:
        note = Note.objects.get(id=note_key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    note.is_public = is_public
    note.save()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_note(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    note_key = json_dict.get('note_key', None)
    if not note_key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    Note.objects.filter(id=note_key).delete()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def query_note(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    section_key = json_dict.get('section_key', None)
    if not section_key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    notes = Note.objects.filter(section__id=section_key)
    data = list()
    for note in notes:
        p = dict()
        p['key'] = note.id
        p['section_key'] = note.section.id
        p['user_key'] = note.user.id
        p['username'] = note.user.username
        p['content'] = note.content
        p['is_public'] = note.is_public
        p['UpdateTime'] = note.UpdatedAt
        p['likes_number'] = len(note.likes.all())
        q = list()
        for epp in note.pictures.all():
            tmp_dict = dict()
            tmp_dict['url'] = epp.url
            tmp_dict['key'] = epp.id
            tmp_dict['file_name'] = epp.file_name
            q.append(tmp_dict)
        p['pictures'] = q
        q = list()
        for comment in note.comments.all():
            tmp_dict = dict()
            tmp_dict['key'] = comment.id
            tmp_dict['note_key'] = comment.note.id
            tmp_dict['user_key'] = comment.user.id
            tmp_dict['content'] = comment.content
            tmp_dict['UpdateTime'] = comment.UpdatedAt
            o = list()
            for pic in comment.pictures.all():
                tmp_dict2 = dict()
                tmp_dict2['url'] = pic.url
                tmp_dict2['key'] = pic.id
                tmp_dict2['file_name'] = pic.file_name
                o.append(tmp_dict2)
            tmp_dict['pictures'] = o
            q.append(tmp_dict)
        p['comments'] = q
        data.append(p)
    return JsonResponse({'code': 200, 'message': '请求成功', 'data': data})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def vote_note(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    note_key = json_dict.get('note_key', None)
    user_key = json_dict.get('user_key', None)
    if not user_key or not note_key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    likes = NoteLikes.objects.filter(user__id=user_key, note__id=note_key)
    if len(likes) == 0:
        try:
            user = MyUser.objects.get(id=user_key)
            note = Note.objects.get(id=note_key)
        except Exception:
            return JsonResponse({'code': 500, 'message': '请求参数错误'})
        like = NoteLikes.objects.create(user=user, note=note)
        like.save()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def cancel_note(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    note_key = json_dict.get('note_key', None)
    user_key = json_dict.get('user_key', None)
    if not user_key or not note_key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    NoteLikes.objects.filter(user__id=user_key, note__id=note_key).delete()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def query_notelikes(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    user_key = json_dict.get('user_key', None)
    try:
        user = MyUser.objects.get(id=user_key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    data = list()
    for notelike in user.likes.all():
        data.append(notelike.note.id)
    return JsonResponse({'code': 200, 'message': '请求成功', 'data': data})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def add_comment(request):
    user_key = request.POST.get("user_key")
    content = request.POST.get("content")
    note_key = request.POST.get("note_key")
    files = request.FILES.getlist("file")
    if not user_key or not content or not note_key or not files:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    try:
        user_key = int(user_key)
        note_key = int(note_key)
        myuser = MyUser.objects.get(id=user_key)
        note = Note.objects.get(id=note_key)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    comment = Comment.objects.create(content=content, user=myuser, note=note)
    comment.save()
    for i in range(len(files)):
        f = files[i]
        url = static_file_path + 'comment_picture/' + str(comment.id) + '_' + str(i) + '_' + f.name
        np = CommentPicture.objects.create(url=url, file_name=f.name, comment=comment)
        np.save()
        d = open(url, 'wb+')
        for chunk in f.chunks():
            d.write(chunk)
        d.close()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def delete_comment(request):
    try:
        json_dict = json.loads(request.body)
    except Exception:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    comment_key = json_dict.get('comment_key', None)
    if not comment_key:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    Comment.objects.filter(id=comment_key).delete()
    return JsonResponse({'code': 200, 'message': '请求成功'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def calc_example(request):
    manager = ModelManager()
    return manager.work(request)


@api_view(['POST'])
def calc_example_test(request):
    return JsonResponse({'code': 200, 'message': '请求成功'})
